package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import com.gulimall.common.utils.R;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;
    //为什么不放到到常量里面？
    private final String CART_PREFIX="gulimall:cart";
    /**
     * 添加购物车
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations operations = getCardOps();
        String string = (String) operations.get(skuId.toString());
        if(!StringUtils.isEmpty(string)){
            //购物车中有次商品，修改数量
            CartItem cartItem = JSON.parseObject(string, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            operations.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
        CartItem cartItem=new CartItem();
        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            //远程调用查到sku的基本信息
            R skuInfo = productFeignService.getSkuInfo(skuId);
            SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
            });
            //商品添加到购物车
            cartItem.setCheck(true);
            cartItem.setCount(num);
            cartItem.setImage(data.getSkuDefaultImg());
            cartItem.setTitle(data.getSkuTitle());
            cartItem.setSkuId(skuId);
            cartItem.setPrice(data.getPrice());
        }, threadPoolExecutor);

        //远程查询sku组合信息，考虑到多次调用远程服务过于耗时，考虑使用多线程
        CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
            List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
            cartItem.setSkuAttr(skuSaleAttrValues);
        }, threadPoolExecutor);
        CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();
        String s = JSON.toJSONString(cartItem);
        operations.put(skuId.toString(),s);
        return cartItem;
    }

    /**
     * 重定向之后的数据查询
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations operations = getCardOps();
        String object = (String) operations.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(object, CartItem.class);
        return cartItem;
    }

    /**
     * 获取购物车列表
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart=new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            //已登录
            String key=CART_PREFIX+userInfoTo.getUserId();
            //合并未登录状态下的购物车
            List<CartItem> cartItems = getCartItems(CART_PREFIX+userInfoTo.getUserKey());
            if(cartItems!=null&&cartItems.size()>0){
                //合并临时购物车
                for (CartItem cartItem : cartItems) {
                    addToCart(cartItem.getSkuId(),cartItem.getCount());
                }
                //清空临时购物车
                clearCart(CART_PREFIX+userInfoTo.getUserKey());
            }
            //获取合并后的购物车数据
            List<CartItem> cartItems1 = getCartItems(key);
            cart.setItems(cartItems1);

        }
        else{
            //未登录
            String key=CART_PREFIX+userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(key);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 清空购车
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**
     * 是否选中
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations operations = getCardOps();
        operations.put(skuId.toString(),jsonString);
    }

    /**
     * 跟新商品数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations operations = getCardOps();
        operations.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    /**
     * 删除
     * @param skuId
     */
    @Override
    public void delete(Long skuId) {
        BoundHashOperations operations = getCardOps();
        operations.delete(skuId.toString());
    }
    /**
     * 返回当前用户购物车中已选中的购物项
     * @return
     */
    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserKey()==null){
            return null;
        }
        else{
            String key=CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(key);
            List<CartItem> collect = cartItems.stream().map(item->{
                //跟新为最新价格
                // TODO 怎么优化循环的远程服务调用
                R getprice = productFeignService.getprice(item.getSkuId());
                String o = (String) getprice.get("data");
                item.setPrice(new BigDecimal(o));
                return item;
            }).filter(item -> {
                return item.getCheck();
            }).collect(Collectors.toList());
            return collect;
        }

    }

    private BoundHashOperations getCardOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey="";
        if(userInfoTo.getUserId()!=null){
            cartKey=CART_PREFIX+userInfoTo.getUserId();
        }
        else{
            cartKey=CART_PREFIX+userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> stringObjectObjectBoundHashOperations = redisTemplate.boundHashOps(cartKey);
        return stringObjectObjectBoundHashOperations;
    }

    /**
     * 获取指定购物车中的数据
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if(values!=null&&values.size()>0){
            List<CartItem> collect = values.stream().map(item -> {
                String s = (String) item;
                CartItem cartItem = JSON.parseObject(s, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
